package controllers

import (
	"book-app/models"
	beego "github.com/beego/beego/v2/server/web"
	"math"
)

type BookController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type JsonPage struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Sumpage int         `json:"sumpage"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
}

func (c *BookController) List() {
	page, _ := c.GetInt("page", 1)
	size := 5
	var count int64
	models.DB.Model(&models.Book{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if sumpage > page {
		sumpage = page
	}
	var allbook []models.Book
	err := models.DB.Find(&allbook).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "询查失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonPage{
			Code:    200,
			Msg:     "询查成功",
			Data:    allbook,
			Page:    page,
			Sumpage: sumpage,
			Size:    size,
			Count:   count,
		}
		c.ServeJSON()
	}
}
